# -*- coding: utf-8 -*-
from typing import Optional
from xml.etree.ElementTree import Element, SubElement, tostring
from xml.dom import minidom

class PomXmlUtil:
    def create_pom_xml(self,group_id, artifact_id, version, packaging, properties=None, modules=None, dependencies=None):
        """
        动态生成 pom.xml 文件
        :param group_id: 项目 groupId
        :param artifact_id: 项目 artifactId
        :param version: 项目版本
        :param packaging: 项目打包方式
        :param properties: 属性字典，例如 {"java.version": "1.8"}
        :param modules: 模块列表，例如 ["module1", "module2"]
        :param dependencies: 依赖列表，例如 [{"groupId": "org.junit", "artifactId": "junit", "version": "4.12"}]
        :return: 格式化后的 XML 字符串
        """
        # 创建根元素
        project = Element("project", xmlns="http://maven.apache.org/POM/4.0.0")
        project.set("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance")
        project.set("xsi:schemaLocation", "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd")

        # 添加基本信息
        SubElement(project, "modelVersion").text = "4.0.0"
        SubElement(project, "groupId").text = group_id
        SubElement(project, "artifactId").text = artifact_id
        SubElement(project, "version").text = version
        if packaging!=None and len(packaging)>0:
            SubElement(project, "packaging").text = packaging

        # 添加 properties
        if properties:
            self.add_properties(project, properties)

        # 添加 modules
        if modules:
            self.add_modules(modules, project)

        # 添加 dependencies
        if dependencies:
            self.add_dependencies(dependencies, project)

        return project

    def add_dependencies(self, dependencies, project):
        # 查找是否已存在 <dependencies> 元素
        deps_element = project.find("dependencies")
        if deps_element is None:
            # 如果不存在，则创建 <dependencies> 元素
            deps_element = SubElement(project, "dependencies")
        for dep in dependencies:
            dep_element = SubElement(deps_element, "dependency")
            SubElement(dep_element, "groupId").text = dep.get("groupId")
            SubElement(dep_element, "artifactId").text = dep.get("artifactId")
            SubElement(dep_element, "version").text = dep.get("version")

    def add_dependencie(self, dependencie, project):
        dependencies=[]
        dependencies.append(dependencie)
        self.add_dependencies(dependencies,project)

    def add_modules(self, modules, project):
        modules_element = SubElement(project, "modules")
        for module in modules:
            SubElement(modules_element, "module").text = module

    def add_properties(self, project, properties):
        props_element = SubElement(project, "properties")
        for key, value in properties.items():
            SubElement(props_element, key).text = value

    def pom_str(self,project:Optional[Element] =None):
        # 格式化 XML
        rough_string = tostring(project, 'utf-8')
        parsed = minidom.parseString(rough_string)
        return parsed.toprettyxml(indent="    ")

    def save_pom_xml(self,file_path, xml_content):
        pretty_xml=xml_content
        if isinstance(xml_content,Element):
            pretty_xml=self.pom_str(xml_content)

        if "</packaging>" in pretty_xml:
            pretty_xml = pretty_xml.replace("</packaging>", "</packaging>\n")
        else:
            pretty_xml = pretty_xml.replace("</version>", "</version>\n")

        pretty_xml = pretty_xml.replace("</properties>", "</properties>\n\n")
        pretty_xml = pretty_xml.replace("</modules>", "</modules>\n\n")
        pretty_xml = pretty_xml.replace("</dependencies>", "</dependencies>\n\n")
        """
        将生成的 XML 内容保存到文件
        :param file_path: 文件路径
        :param xml_content: XML 内容
        """
        with open(file_path, "w", encoding="utf-8") as f:
            f.write(pretty_xml)
